package ntd.util.frame.action.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import ntd.action.ActionAbs;
import ntd.action.bo.ActionInfo;
import ntd.action.bo.ActionOutBo;
import ntd.util.UtilCatch;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.data.factory.FactoryData;

import java.sql.SQLException;
import java.util.List;

public class ActionComConfig extends ActionAbs {

    @Override
    public ActionInfo info() {
        return new ActionInfo("系统功能配置", "action-com-config", new ActionComConfig());
    }

    @Override
    public ActionOutBo handle() {
        //数据库
        Db use = Db.use(FactoryData.dataSource());

        Entity whereEntity = Entity.create("common_config");
        whereEntity.set("code", actionInBo.getDataCode());

        // 查找对应配置
        List<Entity> entities;
        try {
            entities = use.find(whereEntity);
        } catch (SQLException e) {
            StaticLog.error(e, "[Action][系统功能配置][{}]失败...");
            throw new ComException("数据查询失败，请联系管理员或稍后重试...");
        }

        if (entities.size() < 1) {
            throw new ComException("找不到对应配置信息，请核对后重试...");
        }

        if (entities.size() > 1) {
            throw new ComException("配置信息重复，请核对后重试...");
        }

        Entity entity = entities.get(0);

        if (StrUtil.isNotBlank(actionInBo.getDataStr())) {
            entity.set("val", actionInBo.getDataStr());
            UtilCatch.tryCatchNoRes(() -> use.update(entity, Entity.create("common_config").set("id", entity.get("id"))));
        }

        return new ActionOutBo(entity);
    }
}
